package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.LoginFormDTO;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import com.hmdp.mapper.UserMapper;
import com.hmdp.service.IUserService;
import com.hmdp.utils.JWTUtils;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RegexUtils;
import com.hmdp.utils.SystemConstants;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import javax.crypto.SecretKey;
import javax.servlet.http.HttpSession;
import java.time.Duration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    private final StringRedisTemplate stringRedisTemplate;
    private final SecretKey secretKey;

    @Override
    public Result sendCode(String phone) {
        if (RegexUtils.isPhoneInvalid(phone)) {
            return Result.fail("手机号格式错误！");
        }
        String code = RandomUtil.randomNumbers(6);
        String key = RedisConstants.LOGIN_CODE_KEY + phone;
        stringRedisTemplate.opsForValue().set(key, code, Duration.ofMinutes(RedisConstants.LOGIN_CODE_TTL));
//        session.setAttribute("code", code);
        log.info("发送验证码成功，验证码：{}", code);
        return Result.ok();
    }

    @Override
    public Result login(LoginFormDTO loginForm) {
        if (loginForm.getPassword() == null && loginForm.getCode() == null) {
            log.error("登录失败！你没有采取任何一种登录方式");
            return Result.fail("登录失败！你没有采取任何一种登录方式");
        }
        //验证码登录
        if (loginForm.getCode() != null) {
            //校验手机号
            if (RegexUtils.isPhoneInvalid(loginForm.getPhone())) {
                log.error("手机号格式错误！");
                return Result.fail("手机号格式错误！");
            }
            //redis存储code的key
            String key = RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone();
            //根据key获取验证码
            String cacheCode = stringRedisTemplate.opsForValue().get(key);
            if (cacheCode != null && cacheCode.equals(loginForm.getCode())) {
                //查询用户是否存在
                User user = query().eq("phone", loginForm.getPhone()).one();
                if (user == null) {
                    //不存在就创建，也就是自动注册
                    user = createUserWithPhone(loginForm);
                }
                UserDTO userDTO = new UserDTO();
                BeanUtils.copyProperties(user, userDTO);
                Map<String, Object> userMap = BeanUtil.beanToMap(
                        userDTO,
                        new HashMap<>(),
                        CopyOptions.create()
                                .setIgnoreNullValue(true)
                                .setFieldValueEditor((fieldName, fieldValue) -> fieldValue.toString())
                );
//                long currentTime = System.currentTimeMillis();
//                userMap.put("createTime", currentTime);
                String token = JWTUtils.createJWT(
                        secretKey,
//                        currentTime + Duration.ofHours(RedisConstants.LOGIN_USER_TTL).toMillis(),
                        userMap
                );
                String tokenKey = RedisConstants.LOGIN_USER_KEY + token;
                stringRedisTemplate.opsForHash().putAll(tokenKey, userMap);
                stringRedisTemplate.expire(tokenKey, Duration.ofHours(RedisConstants.LOGIN_USER_TTL));
                log.info("手机验证码登录成功，用户：{}, token：{}", userDTO, token);
                //登录成功要删除redis中的验证码
                stringRedisTemplate.delete(RedisConstants.LOGIN_CODE_KEY + loginForm.getPhone());
                return Result.ok(token);
            } else {
                log.error("验证码错误，cacheCode: {}, code: {}", cacheCode, loginForm.getCode());
                return Result.fail("验证码错误");
            }
        }
        log.info("功能未完善");
        return null;
    }

    @Override
    public List<User> queryTop5ByIds(List<String> ids) {
        return baseMapper.queryTop5ByIds(ids);
    }

    private User createUserWithPhone(LoginFormDTO loginForm) {
        User user = new User();
        user.setPhone(loginForm.getPhone());
        user.setNickName(SystemConstants.USER_NICK_NAME_PREFIX + RandomUtil.randomString(10));
        save(user);
        return user;
    }
}
